// 专业类别类型
export type Specialty = '配管专业' | '电气专业' | '暖通专业' | '通信专业' | '仪表专业';

// Excel 工作表类型
interface ExcelSheet {
  sheetName: string;
  rows: (string | number | null)[][];
}

// Excel 数据类型
interface ExcelData {
  sheets: ExcelSheet[];
  electrical: EquipmentData[];
  hvac: EquipmentData[];
  communication: EquipmentData[];
  instrumentation: EquipmentData[];
}

// Excel 原始数据类型
interface RawExcelData {
  sheets: ExcelSheet[];
}

// 从Excel数据中提取设备数据的通用函数
function extractEquipmentData(sheet: ExcelSheet): EquipmentData[] {
  const data: EquipmentData[] = [];
  
  // 找到实际的数据行（跳过标题和空行）
  let dataStartIndex = -1;
  for (let i = 0; i < sheet.rows.length; i++) {
    const row = sheet.rows[i];
    if (row && row[0] && typeof row[0] === 'string' && row[0].includes('设备表及材料表中的实体对象名称')) {
      dataStartIndex = i + 1;
      break;
    }
  }
  
  if (dataStartIndex === -1) {
    // 如果没有找到标准的标题行，尝试从第一行开始（可能已经是数据行）
    dataStartIndex = 0;
  }
  
  // 处理数据行
  for (let i = dataStartIndex; i < sheet.rows.length; i++) {
    const row = sheet.rows[i];
    
    // 跳过空行和标题行
    if (!row || !row[0] || row[0] === null || 
        (typeof row[0] === 'string' && row[0].includes('设备表及材料表中的实体对象名称'))) {
      continue;
    }
    
    // 跳过非设备数据行（如分类标题）
    if (typeof row[0] === 'string' && 
        (row[0].includes('类') || row[0].includes('专业') || row[0].length < 2)) {
      continue;
    }
    
    const item: EquipmentData = {
      设备ID: 'TEMP-0000', // 临时ID，会在后续处理中被替换
      设备表及材料表中的实体对象名称: String(row[0] || ''),
      对应的对象分类标准中的中文名称: String(row[1] || ''),
      序号: String(row[2] || ''),
      分类码: String(row[3] || ''),
      对象命名: String(row[4] || ''),
      位置信息: String(row[5] || ''),
      基础参数: String(row[6] || ''),
      技术规格书: String(row[7] || ''),
      备注: String(row[8] || ''),
    };
    
    data.push(item);
  }
  
  return data;
}

// 根据工作表名称判断专业类别
function getSpecialtyFromSheetName(sheetName: string): Specialty | null {
  if (sheetName.includes('配管')) return '配管专业';
  if (sheetName.includes('电气')) return '电气专业';
  if (sheetName.includes('暖通')) return '暖通专业';
  if (sheetName.includes('通信')) return '通信专业';
  if (sheetName.includes('仪表')) return '仪表专业';
  
  // 如果是机械专业或其他不支持的专业，返回null
  if (sheetName.includes('机制') || sheetName.includes('机械')) return null;
  
  // 其他未知专业也返回null，不进行分类
  return null;
}

export class ExcelDataService {
  private data: ExcelData | null = null;

  async loadExcelFile(file: File): Promise<void> {
    try {
      const formData = new FormData();
      formData.append('file', file);

      const response = await fetch('/api/excel', {
        method: 'POST',
        body: formData,
      });

      if (!response.ok) {
        throw new Error('Failed to upload Excel file');
      }

      const rawData: RawExcelData = await response.json();
      this.data = await this.processExcelData(rawData);
    } catch (error) {
      console.error('加载Excel文件失败:', error);
      throw error;
    }
  }

  async parseExcelData(filename: string): Promise<{
    electricalData: EquipmentData[];
    hvacData: EquipmentData[];
    communicationData: EquipmentData[];
    instrumentationData: EquipmentData[];
  }> {
    try {
      const response = await fetch(`/api/excel?filename=${encodeURIComponent(filename)}`);
      if (!response.ok) {
        throw new Error('Failed to fetch Excel data');
      }
      const rawData: RawExcelData = await response.json();
      this.data = await this.processExcelData(rawData);

      return {
        electricalData: this.getElectricalData(),
        hvacData: this.getHvacData(),
        communicationData: this.getCommunicationData(),
        instrumentationData: this.getInstrumentationData()
      };
    } catch (error) {
      console.error('解析Excel数据失败:', error);
      throw error;
    }
  }

  private async processExcelData(rawData: RawExcelData): Promise<ExcelData> {
    const sheets = rawData.sheets || [];
    const electricalData: EquipmentData[] = [];
    const hvacData: EquipmentData[] = [];
    const communicationData: EquipmentData[] = [];
    const instrumentationData: EquipmentData[] = [];
    
    // 为每个专业维护一个ID计数器
    const idCounters = {
      '配管专业': 1,
      '电气专业': 1,
      '暖通专业': 1,
      '通信专业': 1,
      '仪表专业': 1
    };

    for (const sheet of sheets) {
      // 获取专业类别
      const specialty = getSpecialtyFromSheetName(sheet.sheetName);
      if (!specialty) {
        console.log('跳过非目标表格:', sheet.sheetName);
        continue;
      }

      const rows = sheet.rows || [];
      // 找到数据开始的行
      let dataStartIndex = -1;
      for (let i = 0; i < rows.length; i++) {
        const row = rows[i];
        if (row && row[0] && typeof row[0] === 'string' && 
            (row[0].includes('设备表及材料表中的实体对象名称') || 
             row[0].includes('序号'))) {
          dataStartIndex = i + 1;
          break;
      }
      }

      if (dataStartIndex === -1) {
        console.log('未找到数据起始行:', sheet.sheetName);
        continue;
      }

      // 处理数据行
      for (let i = dataStartIndex; i < rows.length; i++) {
        const row = rows[i];
        if (!row || !row[0] || row[0] === null) continue;
        
        // 跳过标题行和分类标题
        if (typeof row[0] === 'string' && 
            (row[0].includes('设备表及材料表中的实体对象名称') || 
             row[0].includes('序号') ||
             row[0].includes('类') || 
             row[0].includes('专业') || 
             row[0].length < 2)) {
          continue;
        }

        // 生成设备ID
        const specialtyPrefix = specialty === '配管专业' ? 'PP' :
                              specialty === '电气专业' ? 'EL' :
                              specialty === '暖通专业' ? 'HV' :
                              specialty === '通信专业' ? 'CM' :
                              'IN'; // 仪表专业
        const idNumber = idCounters[specialty].toString().padStart(4, '0');
        const deviceId = `${specialtyPrefix}-${idNumber}`;
        
        // 递增ID计数器
        idCounters[specialty]++;

        const device: EquipmentData = {
          设备ID: deviceId,
          设备表及材料表中的实体对象名称: String(row[0] || ''),
          对应的对象分类标准中的中文名称: String(row[1] || ''),
          序号: String(row[2] || ''),
          分类码: String(row[3] || ''),
          对象命名: String(row[4] || ''),
          位置信息: String(row[5] || ''),
          基础参数: String(row[6] || ''),
          技术规格书: String(row[7] || ''),
          备注: row[8] ? String(row[8]) : undefined
        };

        switch (specialty) {
          case '电气专业':
            electricalData.push(device);
            break;
          case '暖通专业':
            hvacData.push(device);
            break;
          case '通信专业':
            communicationData.push(device);
            break;
          case '仪表专业':
            instrumentationData.push(device);
            break;
        }
      }
    }

    return {
      sheets,
      electrical: electricalData,
      hvac: hvacData,
      communication: communicationData,
      instrumentation: instrumentationData
    };
  }

  getData(): ExcelData | null {
    return this.data;
  }

  getElectricalData(): EquipmentData[] {
    return this.data?.electrical || [];
  }

  getHvacData(): EquipmentData[] {
    return this.data?.hvac || [];
  }

  getCommunicationData(): EquipmentData[] {
    return this.data?.communication || [];
  }

  getInstrumentationData(): EquipmentData[] {
    return this.data?.instrumentation || [];
  }

  getAllData(): EquipmentData[] {
    if (!this.data) return [];
    return [
      ...this.data.electrical,
      ...this.data.hvac,
      ...this.data.communication,
      ...this.data.instrumentation
    ];
  }

  getDataBySheet(): Record<string, EquipmentData[]> {
    if (!this.data) return {};
    return {
      electrical: this.data.electrical,
      hvac: this.data.hvac,
      communication: this.data.communication,
      instrumentation: this.data.instrumentation
    };
  }
}

export const excelDataService = new ExcelDataService(); 